package com.feib.soeasy.util;

import java.io.IOException;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;


/**
 * @title (#)SpringContextUtil.java<br>
 * @description <br>
 * @author Jimmy Liu<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/14 create by Jimmy Liu<br>
 */
@Service("springContextUtil")
public class SpringContextUtil implements ApplicationContextAware {

    protected static Logger logger = LoggerFactory.getLogger(SpringContextUtil.class);

    private static Properties props;

    private static ApplicationContext applicationContext;

    /* (non-Javadoc)
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        SpringContextUtil.applicationContext = applicationContext;
        try
        {
            loadProperties();
        }
        catch (IOException e)
        {
            throw new BeanCreationException("讀取Properties 檔案發生錯誤", e);
        }
    }

    public static Object getBean(String name)
    {
        try
        {
            Object bean =  applicationContext.getBean(name);

            if (null == bean)
            {
                logger.debug("由Spring Context 取名稱["+ name+ "] Bean 為 null");
            }
            return bean;
        }
        catch(Exception ex)
        {

            return null;
        }
    }


    private static void loadProperties() throws IOException
    {
        props = new Properties();
        Resource resource =  applicationContext.getResource("classpath:spring-config.properties");        
        props.load(resource.getInputStream());
    }

    public static String getProperty(String name)
    {
        return props.getProperty(name);
    }

}
